package admin

import (
	"errors"
	"parking-lot-go-admin/model"
)

type AdminStruct struct {
	Id       int    `json:"id" gorm:"type:int(11) auto_increment; NOT NULL; primary_key"`
	GroupId  int    `json:"group_id" gorm:"type:int(11);  COMMENT:'用户组'"`
	Username string `json:"username" gorm:"type:varchar(32);  COMMENT:'用户名'"`
	Password string `json:"password" gorm:"type:varchar(32);  COMMENT:'密码'"`
	Salt     string `json:"salt" gorm:"type:varchar(30); COMMENT:'密码盐'"`
	Status   int    `json:"status" gorm:"type:varchar(30); COMMENT:'状态'"`
}

func (c *AdminStruct) TableName() string {
	return "admin"
}

// 创建用户
func (c *AdminStruct) CreateUser(data AdminStruct) error {
	if err := model.Db.Create(&data).Error; err != nil {
		return err
	}

	var adminTokenStruct AdminTokenStruct
	if err := adminTokenStruct.CreateAccessToken(data.Id); err != nil {
		return err
	}

	return nil
}

// 查询用户信息
func (c *AdminStruct) FindUser(id int) (string, error) {
	var adminStruct AdminStruct
	if err := model.Db.Table(c.TableName()).Where("id", id).First(&adminStruct).Error; err != nil {
		return "", errors.New("用户不存在")
	}
	return adminStruct.Username, nil
}
